import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import {
  NzDropdownContextComponent,
  NzDropdownService,
  NzFormatEmitEvent,
  NzTreeComponent,
  NzTreeNode
} from 'ng-zorro-antd';
import { SystemConfigService } from '@core/services/system-config.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-menus',
  templateUrl: './menus.component.html',
  styleUrls: ['./menus.component.less']
})
export class MenusComponent implements OnInit {
  @ViewChild('treeCom') treeCom: NzTreeComponent;
  validateForm: FormGroup;
  dropdown: NzDropdownContextComponent;
  // actived node
  activedNode: NzTreeNode;
  nodes = [];
  event: NzTreeNode;

  currentMenuInfo: any = {
    id: '',
    name: '',
    action: '',
    style: '',
    sort: '',
  };

  constructor(
    private nzDropdownService: NzDropdownService,
    private systemService: SystemConfigService,
    private fb: FormBuilder,
  ) {}

  openFolder(data: NzTreeNode | NzFormatEmitEvent): void {
    // do something if u want
    if (data instanceof NzTreeNode) {
      data.isExpanded = !data.isExpanded;
    } else {
      data.node.isExpanded = !data.node.isExpanded;
    }
  }

  activeNode(data: NzFormatEmitEvent): void {
    if (this.activedNode) {
      // delete selectedNodeList(u can do anything u want)
      this.treeCom.nzTreeService.setSelectedNodeList(this.activedNode);
    }
    data.node.isSelected = true;
    this.activedNode = data.node;
    this.event = data.node;
    // add selectedNodeList
    this.treeCom.nzTreeService.setSelectedNodeList(this.activedNode);

    this.currentMenuInfo = {
      id: this.activedNode.origin.id,
      name: this.activedNode.origin.title,
      action: this.activedNode.origin.action,
      style: this.activedNode.origin.style,
      sort: this.activedNode.origin.sort,
    };

    console.log('this.currentMenuInfo');
    console.log(this.activedNode);
    console.log('this.currentMenuInfo');
  }

  // 点击节点右键弹出框
  contextMenu($event: MouseEvent, template: TemplateRef<void>): void {
    this.dropdown = this.nzDropdownService.create($event, template);
  }


  selectDropdown( type: string): void {
    this.dropdown.close();
    const menuInfo = {
      menuType: type === 'folder' ? 0 : 1,
      name: type === 'folder' ? '模块' : '权限',
      parentId: this.event.key,
    };

    this.systemService.updateMenuInfo(menuInfo).then((response: any) => {
      console.log(response);
      this.ngOnInit();
    }, error => {
      console.log(error);
    });
  }

  // 右键弹出框--删除节点操作
  deleteNode() {
    this.dropdown.close();
    this.systemService.deleteNode(this.event.key).then(response => {
      console.log(response);
      this.ngOnInit();
    }, error => {
      console.log(error);
    });
  }

  // 把菜单数据处理成树形结构
  createTreeData(data) {
    const treeData = [];
    if (data.length > 0) {
      for (const item of data) {
        if (!item.parent) {
          const obj: any = {
            parent: '系统菜单',
            title: item.text,
            key: item.id,
            typeName: item.typeName,
            action: item.action,
            style: item.style,
            id: item.id,
            sort: item.sort
          };
          treeData.push(obj);
        }
      }
      this.run(data, treeData);
    }
    return treeData;
  }

  // 检测并循环添加children
  run(resData, chiArr) {
    if (resData.length > 0) {
      if (chiArr) {
        for (const value of chiArr) {
          for (const list of resData) {
            if (value.id === list.parent) {
              const obj = {
                title: list.text,
                parent: list.parent,
                key: list.id,
                typeName: list.typeName,
                action: list.action,
                style: list.style,
                typeId: list.typeId,
                id: list.id,
                sort: list.sort
              };
              if (!value.children) {
                value.children = [];
              }
              value.children.push(obj);
            }
          }
          this.run(resData, value.children);
        }
      }
    }
  }

  ngOnInit() {
    // 获取菜单数的数据
    this.systemService.getMenusTree().then((response: any) => {
        this.nodes = this.createTreeData(response.data);
        console.log(this.nodes);
        this.nodes.map((item: any) => {
          if (item.children) {
            item.expanded = true;
            item.children.map((value: any) => {
              value.children ? value.expanded = true : value.isLeaf = true;
            });
          } else {
            item.isLeaf = true;
          }
          return item;
        });
      }, reject => {
        console.log(reject);
      }
    );

    this.validateForm = this.fb.group({
      name: [null],
      action: [null],
      style: [null],
      sort: [null],
      required: [false]
    });
  }

  // 提交表单
  submitForm(data): void {
    this.systemService.updateMenuInfo(data).then(response => {
      this.ngOnInit();
      console.log(response);
    }, error => {
      console.log(error);
    });
  }

}
